package com.ty.utils;

import java.sql.*;
import java.io.InputStream;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {
    private static String url;
    private static String username;
    private static String password;
    private static String driver;

    // 静态代码块，在类加载时执行，只执行一次
    static {
        try {
            // 1.创建Properties集合类
            Properties properties = new Properties();

            // 2.加载文件
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);

            // 3.获取数据，赋值
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");

            // 4.注册驱动
            Class.forName(driver);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return 数据库连接对象
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放资源
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 记录数据库操作日志
     * @param operationType 操作类型，如 "INSERT", "UPDATE", "DELETE"
     * @param tableName 操作的表名
     * @param operationDetail 操作的详细信息
     */
    public static void logOperation(String operationType, String tableName, String operationDetail) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();
            String sql = "INSERT INTO db_operation_log (operation_type, table_name, operation_detail) VALUES (?, ?, ?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, operationType);
            ps.setString(2, tableName);
            ps.setString(3, operationDetail);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(null, ps, conn);
        }
    }
}